import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Icon, Modal, Form, Input, Select, Upload } from 'antd';
import Service from '@/public/http/services';
import style from './index.css';
const { TextArea } = Input;
const { Option } = Select;
const CreateModal: React.FC<any> = ({ formData, roles, visible, title, onOK, onCancel, form, dispatch }) => {
    useEffect(() => {
        dispatch({
            type: 'expert/fetchRoles'
        })
        if (formData && Object.keys(formData).length) setCurFileList([{ uid: formData.id, url: formData.hPortrait }] as any)
    }, [dispatch, formData])

    const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    }

    const { getFieldDecorator } = form;
    const [loading, setLoading] = useState(false);

    const [curFileList, setCurFileList] = useState([]);

    const uploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurFileList([{
            uid,
            name,
            url: curFileUrl,
        }] as any);
    }

    const handleChange = (file) => { }

    const [curActionUrl, setCurActionUrl] = useState();
    const [curUploadData, setCurUploadData] = useState({});
    const [curFileUrl, setCurUrl] = useState('');
    const beforeUpload = async (file, fileList) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurUrl(host + '/' + key)
        setCurUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status : '200',
            signature
        });
        return true;
    }

    const removeSuccess = () => {
        setCurFileList([] as any);
    }

    /**
     * @desc 文章插图上传配置
     */
    // const uploadInfo = JSON.parse(Cookie.get('upload'));
    // const actionUrl = uploadInfo.host;
    // const data = { ...uploadInfo, host: null }
    // const actionUrl = '';
    const upload: any = {
        name: 'file',
        // action: `${cst.domain}/file/uploadFile`,//上传接口，成功后返回该图片服务器地址
        action: curActionUrl,//上传接口，成功后返回该图片服务器地址
        listType: 'picture-card',
        headers: {
            authorization: 'authorization-text',
        },
        onSuccess: uploadSuccess,
        onChange: handleChange,
        beforeUpload: beforeUpload,
        onRemove: removeSuccess,
        data: curUploadData
    }

    return (
        <Modal
            visible={visible}
            title={title}
            okText={'保存'}
            cancelText={'取消'}
            onOk={() => {
                setCurFileList([])
                onOK && onOK(form, { files: curFileList, roles })
            }}
            onCancel={() => {
                setCurFileList([])
                onCancel(form)
            }}
            width={'65%'}
        >
            <Form.Item {...formItemLayout} label={'姓名'}>
                {
                    getFieldDecorator('nickname', {
                        initialValue: formData.nickname,
                        rules: [{ required: true, message: '请输入姓名' }],
                    })(<Input className={style.w220} placeholder={'请输入姓名'} />)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'头像'}>
                {
                    getFieldDecorator('hPortrait', {
                        initialValue: curFileList.length ? (curFileList[0] as any).url : '',
                        rules: [{ required: true, message: '请上传头像' }],
                        getValueFromEvent: (e) => {
                            return e.fileList
                        }
                    })(<Upload
                        className={style['upload-btn']}
                        {...upload}
                        fileList={curFileList}
                    >
                        <div key={'upload-btn'}>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className='ant-upload-text'>上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'家幼职级'}>
                {
                    getFieldDecorator('expertRoleId', {
                        initialValue: formData.expertRoleId,
                        rules: [{ required: true, message: '请选择家幼职级' }],
                    })(<Select className={style.w220} placeholder={'请选择家幼职级'}>
                        {
                            roles!.map((role: any, index: number) => <Option key={`option-${index}`} value={role.id}>{role.name}</Option>)
                        }
                    </Select>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'专家介绍'}>
                {
                    getFieldDecorator('expertDesc', {
                        initialValue: formData.expertDesc,
                    })(<TextArea placeholder={'请输入专家介绍'} />)
                }
            </Form.Item>
        </Modal>
    );
}
const WrappedCreateModal = Form.create<any>({ name: 'modalForm' })(CreateModal);
export default connect((state: any) => {
    return {
        roles: state.expert.roles
    }
})(WrappedCreateModal);
